package c5_2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

/**
 * @author： pang-yun
 * @date： 2021-09-07 09:59
 * 功能目的 ：用于 非阻塞模式测试
 * serverSocketChannel 设为非阻塞  accept可以不断接收  socketChannel 设为非阻塞  可以不断读取
 */
@Slf4j
public class NioServerP {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(9999));

        ArrayList<SocketChannel> channelArrayList = new ArrayList<>();

        while (true){
            SocketChannel sc = ssc.accept();
            if (sc!=null){
                log.info("connected....{}",sc);
                sc.configureBlocking(false);
                channelArrayList.add(sc);
            }

            for (SocketChannel channel: channelArrayList){
                int read = channel.read(byteBuffer);
                if (read>0){
                    byteBuffer.flip();
                    while (byteBuffer.hasRemaining()){
                        byte b = byteBuffer.get();
                        System.out.print((char) b);
                    }
                    byteBuffer.clear();
                }
            }

        /*    channelArrayList.stream().forEach(channel -> {
                try {
                    int read = channel.read(byteBuffer);
                    if (read>0){
                        byteBuffer.flip();
                        while (byteBuffer.hasRemaining()){
                            byte b = byteBuffer.get();
                            System.out.println((char) b);
                        }
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });*/
        }

    }
}
